package com.dw.wms.basedata.controller;

import com.dw.wms.basedata.domain.Spu;
import com.dw.wms.basedata.service.SpuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/basedata/spu")
@RequiredArgsConstructor
@Api(tags = "SPU管理")
public class SpuController {

    private final SpuService spuService;

    /**
     * 获取所有SPU列表
     */
    @GetMapping
    @ApiOperation("获取SPU列表")
    public ResponseEntity<List<Spu>> getAllSpus() {
        List<Spu> spus = spuService.list();
        return ResponseEntity.ok(spus);
    }

    /**
     * 根据ID获取SPU详情
     */
    @GetMapping("/{id}")
    @ApiOperation("根据ID获取SPU详情")
    public ResponseEntity<Spu> getSpuById(@PathVariable Long id) {
        Spu spu = spuService.getById(id);
        if (spu != null) {
            return ResponseEntity.ok(spu);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 创建新SPU
     */
    @PostMapping
    @ApiOperation("创建SPU")
    public ResponseEntity<Spu> createSpu(@RequestBody Spu spu) {
        // 检查必要字段
        if (spu.getSpuCode() == null || spu.getSpuName() == null) {
            return ResponseEntity.badRequest().build();
        }

        // 设置默认状态
        if (spu.getStatus() == null) {
            spu.setStatus("0");
        }

        boolean saved = spuService.save(spu);
        if (saved) {
            Spu savedSpu = spuService.getById(spu.getId());
            return ResponseEntity.status(HttpStatus.CREATED).body(savedSpu);
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新SPU信息
     */
    @PutMapping("/{id}")
    @ApiOperation("更新SPU信息")
    public ResponseEntity<Spu> updateSpu(@PathVariable Long id, @RequestBody Spu spu) {
        // 检查要更新的SPU是否存在
        Spu existingSpu = spuService.getById(id);
        if (existingSpu == null) {
            return ResponseEntity.notFound().build();
        }

        // 设置ID确保更新正确的记录
        spu.setId(id);

        // 执行更新操作
        boolean updated = spuService.updateById(spu);
        if (updated) {
            // 返回更新后的完整对象
            Spu updatedSpu = spuService.getById(id);
            return ResponseEntity.ok(updatedSpu);
        } else {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 删除SPU
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除SPU")
    public ResponseEntity<Void> deleteSpu(@PathVariable Long id) {
        boolean deleted = spuService.removeById(id);
        if (deleted) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}

